<?php
class UserController extends Zend_Controller_Action {

    public function init(){

        Zend_Loader::loadClass('User');
    }
    public function registerAction(){

        $this->view->title = 'Register';

        if($this->_request->isPost()){

            if($this->_request->getPost('agree') == 'on'){
                if($_POST['pass'] == $_POST['passAgain']){

                    //Filter datas of input
                    Zend_Loader::loadClass('PostFilter');
                    PostFilter::filter();

                    //Validate datas of input
                    Zend_Loader::loadClass('Zend_Validate_Regex');


                    $mailValidator = new Zend_Validate_Regex('/^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[a-z]{2,4}$/');

                    $nameValidator = new Zend_Validate_Regex('/^[a-z0-9_]{5,30}$/');
                     
                    $passValidator = new Zend_Validate_Regex('/^.{5,30}/');

                    $user = new User();
                    $mailValid = $mailValidator->isValid($this->_request->getPost('mail'));
                    $mailUnique = $user->checkUnique('mail', $this->_request->getPost('mail'));
                    $nameValid = $nameValidator->isValid($this->_request->getPost('name'));
                    $nameUnique = $user->checkUnique('name', $this->_request->getPost('name'));
                    $passValid = $passValidator->isValid($this->_request->getPost('pass'));

                    if(!$mailValid || !$nameValid || !$passValid || !$nameUnique || !$mailUnique){

                        if(!$mailValid)
                        Message::setMessage('Valid email address required', 'error');
                        if(!$nameValid)
                        Message::setMessage('5 to 30 characters of "a-z","0-9" and "_" are only allowed within "Username"', 'error');
                        if(!$passValid)
                        Message::setMessage('5 to 30 characters are only allowed within "Password"', 'error');
                        if(!$nameUnique)
                        Message::setMessage('This username has already been registered.', 'error');
                        if(!$mailUnique)
                        Message::setMessage('This email has already been registered.', 'error');

                         
                         
                    }else{
                         

                        $data = array(
                        'name' => $this->_request->getPost('name'),
                        'pass' => md5($this->_request->getPost('pass')), 
                        'mail' => $this->_request->getPost('mail'),
                        'created' => time(),
                        'ip_address' => $_SERVER['REMOTE_ADDR'],              
                        );
                        $user = new User();
                        $user->insert($data);

                        Message::setMessage('Congratulations, you have been registered successfully.');
                        $this->_redirect('/index');

                    }
                }else{

                    Message::setMessage('Two Passwords do not match.', 'error');
                }
            }else{

                Message::setMessage('To sign up, you must accept the policy of this site.', 'error');
            }

             
        }

        $this->view->mail = $this->_request->getPost('mail');
        $this->view->name = $this->_request->getPost('name');
         
         
    }

    public function loginAction(){

        $this->view->title = "Log In";
        $this->view->messages = array();
        if($this->_request->isPost()){

            //Filter datas of inputs
            Zend_Loader::loadClass('PostFilter');
            PostFilter::filter();

            //Authenticate user login
            $name = $this->_request->getPost('name');
            $pass = md5($this->_request->getPost('pass'));
            if(empty($name)){

                $this->view->messages += (array)'Username cannot be empty.';
            }else{

                Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
                $db = Zend_Registry::get('db');
                $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                $authAdapter->setTableName('user')
                ->setIdentityColumn('name')
                ->setCredentialColumn('pass')
                ->setIdentity($name)
                ->setCredential($pass);
                $auth = Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);

                if(!$result->isValid()){
                     
                    Message::setMessage('Invalid username or password', 'error');
                }
                else{


                    //Save user's information into session

                    $data = $authAdapter->getResultRowObject(null,'pass');
                    $auth->getStorage()->write($data);

                     

                    //Update user's information
                    $id = $auth->getIdentity()->id;
                    $name = $auth->getIdentity()->name;
                     
                    $user = new User();
                     
                    $data = array(
                            'login' => time(),
                            'ip_address' => $_SERVER['REMOTE_ADDR'],
                    );
                    $user->update($data,'id = '.$id);

                    Message::setMessage('Welcome back <i>'.$name.'</i>, you have been logged in successfully.');
                    $this->_redirect('/resume/index');


                }


            }
        }

    }

    public function logoutAction(){

        $auth = Zend_Auth::getInstance();
        $name = $auth->getIdentity()->name;
        $auth->clearIdentity();
        Message::setMessage('<i>'.$name.'</i>, you have been logged out.');
        $this->_redirect('/index');
    }
}
